import React, { Component } from 'react';
import { Table, Input, Button, Popconfirm, Form, Select, Modal,  Divider } from 'antd';
import Content from "../../components/Content/Content";
import moment from "moment";
const EditableContext = React.createContext();
const { Option } = Select;
const InputGroup = Input.Group;
const { TextArea } = Input;
const { Item } = Form;

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);
function handleChange(value) {
  console.log(`selected ${value}`);
}
class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title}不能为空！`,
            },
          ],
          initialValue: record[dataIndex],
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        editable: false,
        fixed: 'left',
        width:120,
      },
      {
        title: '筛选菌株编号',
        dataIndex: 'sxjj_id',
        editable: true,
        fixed: 'left',
        width:200,
      },
      {
        title: '共享单位类型',
        dataIndex: 'out_gxdw',
        render: (text, record) => (
          <Select defaultValue={text}
          mode="tags"
          style={{ width: "100%" }}
          onChange={value => this.setState({out_gxdw: value})}
          tokenSeparators={[","]}
          showArrow={true}
        >
          <Option value="BSHI">本室</Option>
          <Option value="BSUO">本所</Option>
          <Option value="WDW">外单位</Option>
          <Option value="QT">其他</Option>
        </Select>
              )
      },
      {
        title: '共享单位名称',
        dataIndex: 'unit_name',
        editable: true,
      },
      
      {
        title: '共享课题组名称',
        dataIndex: 'out_group',
        editable: true,
      },
      {
        title: '使用人',
        dataIndex: 'user_share',
        editable: true,
      },
      {
        title: '使用人联系方式',
        dataIndex: 'user_tel',
        editable: true,
      },
      {
        title: '使用人联系邮箱',
        dataIndex: 'user_email',
        editable: true,
      },
      {
        title: '使用时间',
        dataIndex: 'sevice_time',
        editable: true,
      },
      {
        title: '是否反馈',
        dataIndex: 'is_feedback',
        editable: true,
      },
      {
        title: '反馈时间',
        dataIndex: 'feedback_time',
        editable: true,
      },
      {
        title: '使用结果',
        dataIndex: 'sevice_result',
        editable: true,
      },
      {
        title: '出库人',
        dataIndex: 'worker',
        editable: true,
      },
      {
        title: '出库时间',
        dataIndex: 'delivery_time',
        editable: true,
      },
      {
        title: '备注说明',
        dataIndex: 'remark',
        editable: true,
      },
      {
        title: '筛选方法编号',
        dataIndex: 'm_id',
        editable: true,
      },
      {
        title: '筛选方法名称',
        dataIndex: 'm_name',
        editable: true,
      },
      {
        title: '预计筛选周期',
        dataIndex: 'screen_cycle',
        editable: true,
      },
      {
        title: '筛选结果',
        dataIndex: 'screen_result',
        editable: true,
      },
      {
        title: '操作',
        dataIndex: 'address',
        fixed: 'right',
        width:200,
        render: (text, record) => (
          <span>
            <Button type="dashed" onClick={() => this.showDetailModal(record)}>
              查看
            </Button>
            <Divider type="vertical" />
            <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.id)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      },
    ];

    this.state = {
      dataSource: [],
      newData: {},
      viewData: {},
      visible_detail: false,

      out_gxdw: '',

      selectedRowKeys: [], // Check here to configure the default column
      loading: false,

      keyword: '',

      count: 0,
      pageNum: 1,
      pageSize: 100
    };
  }

  loadData = (current = 1) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    const url = global.api.screeningLibraryShare;
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search: this.state.keyword})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count})
    })
    .catch(err => {
      Modal.error({
        content: '加载数据出错！',
      });
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  handleDelete = id => {
    const dataSource = [...this.state.dataSource];

    // 如果是新数据尚未保存，那么可以直接删除
    if( this.state.newData.id != null ) {
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      return;
    }
    
    const url = global.api.screeningLibraryShare + id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    }) 

  };

  start = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  };

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
  handleAdd = () => {
    const { count, dataSource } = this.state;

    if( this.state.newData.id != null ) {
      Modal.error({
        content: '数据尚未保存！',
      });
      return;
    }

    const initVal = count + 1;
    const newData = {
      id: initVal,
      // out_gxdw: initVal,
      unit_name: initVal,
      out_group: initVal,
      user_share: initVal,
      user_tel: initVal,
      user_email: initVal + '@163.com',
      sevice_time:  moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 
      is_feedback: initVal, // file
      feedback_time: moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 
      sevice_result: initVal, // file
      worker: initVal, // file
      delivery_time:  moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 
      remark : initVal,
      sxjj_id : initVal,
      m_id: initVal,
      m_name: initVal, // file
      screen_cycle : initVal,
      screen_result : initVal,
    }
    this.setState({
      dataSource: [newData, ...dataSource],
      count: count + 1,
      newData: newData
    });

  };

  showDetailModal = (record) => {
    this.setState({
      visible_detail: true,
      viewData: record,
    });
  };
  handleOk = e => {
    this.setState({
      visible_detail: false,
    });
  };
  handleCancel = e => {
    this.setState({
      visible_detail: false,
    });
  };

  handleSave = (row, showAlert) => {
    let dataSource = [...this.state.dataSource];
    let record = null;
    if( row.id != null ) {
      record = row;
    } else {
      record = dataSource[dataSource.length - 1];
    }

    record.out_gxdw = this.state.out_gxdw.length > 0 ? this.state.out_gxdw[0] : '';

    const url = global.api.screeningLibraryShare;
    return global.network.post(url, record)
    .then(res => {  
      const newData = [...this.state.dataSource];
      const index = newData.findIndex(item => record.id === item.id);
      const item = newData[index];
      newData.splice(index, 1, {
        ...item,
        ...record,
      });
      
      this.setState({ dataSource: newData, newData: {} });

      if( showAlert ) {
        Modal.success({
          content: '保存成功!',
        });
      }
    })
    .catch(err => {
      if( showAlert ) {
        Modal.error({
          content: '保存出错，请检查传入的参数是否已经填写！',
        });
      }
    }) 
  };

  render() {
    const { dataSource,loading, selectedRowKeys } = this.state;    
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 }
      }
    };
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          key: record.id,
          handleSave: this.handleSave,
        }),
      };
    });
   
    return (
      <Content>
          <div className="filtrate">
          <p style={{marginLeft:'100px'}}>
          <span className="span">
         <Input placeholder="输入查询内容" style={{ width: 250 }}  onChange={value => this.setState({keyword: value})} />
          </span>
          <span className="span" >
            <Button loading={this.state.loading} type="primary" style={{ width: 80 }} onClick={this.loadData.bind('click', 1)}>
              查询
            </Button>
          </span>
          </p>
        </div>
        <div style={{marginTop: '50px',marginLeft: 16}}>
        <Button onClick={this.handleAdd} type="primary" >
          添加
        </Button>
        <Button disabled={this.state.newData.id == null  } onClick={() => this.handleSave({},true)} type="primary" style={{ marginLeft: 16 }}>
          保存
        </Button>
         </div>

        <Modal
          title="Basic Modal"
          visible={this.state.visible_detail}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
        <Form {...formItemLayout} onSubmit={this.onSubmit} colon={false}>
          <div style={{display:'flex'}}>
            <span style={{flex:'1'}}>
              <Item label="ID"><Input value={this.state.viewData.id} /></Item>
              <Item label="共享单位类型"><Input value={this.state.viewData.out_gxdw} /></Item>
              <Item label="共享单位名称"><Input value={this.state.viewData.unit_name} /></Item>
              <Item label="共享课题组名称"><Input value={this.state.viewData.out_group} /></Item>
              <Item label="使用人"><Input value={this.state.viewData.user_share} /></Item>
              <Item label="使用人联系方式"><Input value={this.state.viewData.user_tel} /></Item>
              <Item label="使用人联系邮箱"><Input value={this.state.viewData.user_email} /></Item>
              <Item label="使用时间"><Input value={this.state.viewData.sevice_time} /></Item>
              <Item label="是否反馈"><Input value={this.state.viewData.is_feedback} /></Item>
              <Item label="反馈时间"><Input value={this.state.viewData.feedback_time} /></Item>
              <Item label="使用结果"><Input value={this.state.viewData.sevice_result} /></Item>
            </span>
            <span style={{flex:'1'}}>
              <Item label="出库人"><Input value={this.state.viewData.worker} /></Item>
              <Item label="出库时间"><Input value={this.state.viewData.delivery_time} /></Item>
              <Item label="备注说明"><Input value={this.state.viewData.remark} /></Item>
              <Item label="筛选菌株编号"><Input value={this.state.viewData.sxjj_id} /></Item>
              <Item label="筛选方法编号"><Input value={this.state.viewData.m_id} /></Item>
              <Item label="筛选方法名称"><Input value={this.state.viewData.m_name} /></Item>
              <Item label="预计筛选周期"><Input value={this.state.viewData.screen_cycle} /></Item>
              <Item label="筛选结果"><Input value={this.state.viewData.screen_result} /></Item>
            </span>
          </div>
        </Form>
        </Modal>

        <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          scroll={{ x: 3500}}
        />

      </Content>
    );
  }
}

const ScreeningSaveInfo = Form.create()(EditableTable);
export default ScreeningSaveInfo;